package com.dpj.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j(topic = "c.TestCountDownLatch")
public class TestCountDownLatch {
    public static void main(String[] args) throws InterruptedException {
      //  method1(); //简单使用

        //等待多线程准备完毕(类似于王者荣耀加载时多人等待加载)
        ExecutorService service = Executors.newFixedThreadPool(10);
        CountDownLatch countDownLatch=new CountDownLatch(10);
        Random r=new Random();
        String[] all=new String[10];
        for (int j = 0; j < 10; j++) {
            int k=j;
            service.submit(()->{
                for (int i = 0; i <= 100; i++) {
                    try {
                        Thread.sleep(r.nextInt(100));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    all[k]=i+"%";
                    System.out.print("\r"+Arrays.toString(all));

                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        System.out.println("\n游戏开始");
        service.shutdown();

    }

    private static void method1() throws InterruptedException {
        CountDownLatch latch=new CountDownLatch(3);
        new Thread(()->{
            log.debug("begin");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            latch.countDown();
            log.debug("end");

        }).start();
        new Thread(()->{
            log.debug("begin");
            try {
                Thread.sleep(1500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            latch.countDown();
            log.debug("end");
        }).start();

        new Thread(()->{
            log.debug("begin");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            latch.countDown();
            log.debug("end");

        }).start();

        log.debug("waiting");
        latch.await();
        log.debug("wait end");
    }
}
